package leetcode.l2;

import java.util.concurrent.*;

/**
 * 两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法，另一个线程将会调用 bar() 方法。
 * 请设计修改程序，以确保 "foobar" 被输出 n 次。
 * 使用CountDownLatch 和 CyclieBarrier
 *
 * @author LiYilin on 2020/3/29
 */
public class L2FooBarSolution3CountDownLatchAndCyclieBarrier {

    private int n;
    private CountDownLatch countDownLatch;
    private CyclicBarrier barrier;


    public L2FooBarSolution3CountDownLatchAndCyclieBarrier(int n) {
        this.n = n;
        countDownLatch = new CountDownLatch(1);
        barrier = new CyclicBarrier(2);
    }

    public void foo(Runnable printFoo) throws InterruptedException, BrokenBarrierException {

        for (int i = 0; i < n; i++) {
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            countDownLatch.countDown();
            barrier.await();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException, BrokenBarrierException {

        for (int i = 0; i < n; i++) {
            System.out.println("bar await");
            countDownLatch.await();
            System.out.println("bar run");
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            countDownLatch = new CountDownLatch(1);
            barrier.await();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        L2FooBarSolution3CountDownLatchAndCyclieBarrier fooBar = new L2FooBarSolution3CountDownLatchAndCyclieBarrier(5);
        //缺少ThreadFactory的实现
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 10, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));

        executor.execute(() -> {
            try {
                fooBar.bar(() -> System.out.println("bar"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        executor.execute(() -> {
            try {
                fooBar.foo(() -> System.out.println("foo"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        executor.shutdown();
    }
}
